import React, { useEffect, useState } from 'react'
import { Card, Form, Button, Input, Select, Table, Row, Col,message } from 'antd'
import { SearchOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom'

//引入列表请求api
import { getHosListRequest, getProvinceRequest, getCityOrDistrictRequest,getChangeStatusRequest } from '@api/hospital/hospitalList'
//引入参数类型
import {
  hospitalListSearchParamsType,
  hospitalListContentType,
  hospitalListItemsType,
  getProvinceReturnType,
} from '@api/hospital/model/hospitalListType'

export default function HospitalList() {
  const [isLoading, setIsLoading] = useState(false)
  //获取路由导航
   const navigate = useNavigate()

  //创建page。limit，状态,用户输入的searchParams
  const [page, setPage] = useState(1)
  const [limit, setLimit] = useState(2)
  const [searchParams, setSearchParams] = useState<hospitalListSearchParamsType>({})

  //设置渲染列表的状态
  const [hospitalList, setHospitalList] = useState<hospitalListContentType>([])
  // console.log(hospitalList);

  //设置总页数状态
  const [total, setTotal] = useState<number>()

  //保存请求到的省份信息
  const [province, setProvince] = useState<getProvinceReturnType>([])
  // console.log(province,'q');
  //保存获取的市信息
  const [city, setCity] = useState<getProvinceReturnType>([])
  // console.log(city);
  //保存获取的区县信息
  const [county, setCounty] = useState<getProvinceReturnType>([])
  //保存获取医院类型
  const [hosType,setHosType] =useState<getProvinceReturnType>([])

  //创建一个from实例，并设置给需要修改的表单
  const [form] = Form.useForm()

  //控制重新渲染的state
  const [reRender, setReRender] = useState(true);
  


  //进入页面时发送请求
  useEffect(() => {
    setIsLoading(true)
    const getHosList = async () => {
      const re = await getHosListRequest(page, limit, searchParams)
      //  console.log(re,'111');
      //设置初始数据渲染
      setHospitalList(re.content)
      //设置总数
      setTotal(re.totalElements)
      setIsLoading(false)
    }
    getHosList()
    //当查询参数发生变化时，监听
  }, [page, limit, searchParams,reRender])

  //进入页面时请求省份
  useEffect(() => {
    // 创建请求省份
    const geiProvince = async () => {
      const re = await getProvinceRequest()
      //  console.log(re,'re');
      setProvince(re)
    }
    geiProvince();
    //获取市级，表单上有个onchange事件
  }, [])

  //进入页面时请求医院类型
  useEffect(() => {
    // 获取医院类型
    const geiHosType = async () => {
      const re = await getCityOrDistrictRequest('10000')
      //  console.log(re,'re');
       setHosType(re)
    }
    geiHosType();
  }, [])

  //1、当点击选省份发生改变时，创建事件
  const getcityList = async (value: string) => {
    //可以拿到一个value，是当前省份value
    // console.log(value);
    // 发送请求
    const citys = await getCityOrDistrictRequest(value)
    setCity(citys)

    // 切换省份时，清空市和县表单
    form.setFieldsValue({ cityCode: null, districtCode: null })
    //并且清除县的下拉数据
    setCounty([])
  }

  //2、点选市的时候获取县区
  const getCountylist = async (value: string) => {
    const county = await getCityOrDistrictRequest(value)
    setCounty(county)
    //完成后，换省市市时优化清空市县信息，重新设置表单，可以使用From.
    //点击切换市的时候
    form.setFieldsValue({ districtCode: null })
  }

  //3、查询信息时，表单完成事件
  const getSearchOnFinish = (value: hospitalListSearchParamsType) => {
    // console.log(value,'va'); 可以拿到查询的参数
    // 保存这个状态
    setSearchParams(value)

  }

  //4.点击清空时，清楚查询信息
  const deletesearchParams=()=>{
    setSearchParams({})
  }

  //5、点击上下线切换状态
  const  changeStatusHandle =(id: string, status: 0 | 1)=>{
    // console.log(id,status,'12131');

      return async()=>{
        console.log(1111,status);
        
        await getChangeStatusRequest(id,status)

        message.success("改变医院上下线状态成功");
         //重新渲染
        setReRender(!reRender);
      }
  }


  const tableData: any[] = [];
  const columns = [
    {
      title: '序号',
      width: 60,
      dataIndex: 'index',
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院log',
      render(_: any, data: any) {
        return (
          <img width={100} src={`data:image/jpeg;base64,${data.logoData}`} alt="" />
        )
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render(_: any, data: any) {
        // console.log(data);
        return data.param.hostypeString
      }

    },
    {
      title: '详细地址',
      render(_: any, data: hospitalListItemsType) {
        return data.param.fullAddress
      }
    },
    {
      title: '状态',
      render(_: any, data: hospitalListItemsType) {
        return data.status === 0 ? '下线' : '上线'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      width: 250,
      fixed: "right" as "right",
      scrollX:true,
      render(_: any,dataT:hospitalListItemsType) {
        // console.log(dataT.status,'T');
        const {id,status,hoscode} = dataT
        return (
          <div>

            <Button type='primary' onClick={()=>{navigate(`/syt/hospital/hospitallist/hospitalShow/${id}`)} } style={{marginRight:'10px'}}>查看</Button>
            <Button type='primary' style={{marginRight:'10px'}} onClick={()=>{navigate(`/syt/hospital/hospitallist/hosScheduling/${hoscode}`)}}>排班</Button>
            <Button type='primary' onClick={changeStatusHandle(id, status === 0? 1:0)}>{status === 0 ? '上线' : '下线'}</Button>
          </div >
        )
      }
    }
  ];

  //1、切换分页逻辑
  const pageChangeHandle = (current: number, pageSize: number) => {
    // console.log(current,pageSize);
    setPage(current);
    setLimit(pageSize)
  }

  
  return (
    <div>
      <Card>
        <Form
          name="basic"
          form={form}
          onFinish={getSearchOnFinish}
        >
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="provinceCode"
              >
                <Select
                  placeholder="请输入省份"
                  allowClear
                  onChange={getcityList}
                >
                  {province.map((item) => {
                    return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="cityCode"

              >
                <Select
                  placeholder="请输入市"
                  allowClear
                  onChange={getCountylist}
                >
                  {city.map((item) => {
                    return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="districtCode"
              >
                <Select
                  placeholder="请输入县/区"
                  allowClear
                >
                  {county.map((item) => {
                    return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                  })}
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hostype"
              >
                <Select
                  placeholder="医院类型"
                  allowClear
                >
                  {hosType.map((item) => {
                    return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="status"
              >
                <Select
                  placeholder="医院状态"
                  allowClear
                >
                  <Select.Option value={0}>上线</Select.Option>
                  <Select.Option value={1}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col >
          </Row>

          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="hosname"
              >
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="hoscode"
              >
                <Input placeholder='医院编号' />
              </Form.Item>
            </Col>

            <Col span={2}>
              <Form.Item >
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />} >
                  查询
                </Button>
              </Form.Item>

            </Col>
            <Col span={2} style={{ marginLeft: "20px" }}>
              <Form.Item >
                <Button type="default" htmlType="reset" onClick={deletesearchParams}>
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>



        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}

          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total: total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [2, 5, 10],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            showTotal(total) {
              return `总共有${total}条数据`
            },
            onChange: pageChangeHandle
          }}
        />
      </Card>
    </div >
  )
}
